package web.get;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Book;
import domain.Chapter;
import domain.User;
import service.BookService;
import service.UserService;
import service.impl.BookServiceImpl;
import service.impl.UserServiceImpl;
import util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/getChapterNameList")
public class GetBookChapterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        Map<String,Object> msg = new HashMap<>(8);
        String bid = request.getParameter("bid");
        User user = ServletUtil.checkLogin(request);
        Book book = ServletUtil.checkBook(user, Integer.parseInt(bid));
        BookService bs = new BookServiceImpl();
        if(book==null){
            msg.put("msg","失败");
            msg.put("isSuccess",false);
            new ObjectMapper().writeValue(response.getOutputStream(),msg);
        }
        List<Chapter> capterNameList = bs.getCapterNameList(book);
        msg.put("msg","成功");
        msg.put("isSuccess",true);
        msg.put("chapterList",capterNameList);
        new ObjectMapper().writeValue(response.getOutputStream(),msg);
    }
}
